<template>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <template #header>
            <el-row :gutter="20">
                <el-col :span="12" :offset="0">用户管理</el-col>
                <el-col :span="12" class="text-right">
                    <el-button type="primary" @click="handleAdd">添加用户</el-button>
                </el-col>
            </el-row>
        </template>
        <!-- card body -->
        <div>

            <el-table :data="userList" v-loading="loading" style="width: 100%">
                <el-table-column fixed label="ID" prop="id" width="80"></el-table-column>
                <el-table-column label="用户名" prop="username" min-width="120"></el-table-column>
                <!-- 添加角色类型列 -->
                <el-table-column label="角色类型" prop="role_type" min-width="120"></el-table-column>
                <!-- 添加创建时间列 -->
                <el-table-column label="创建时间" prop="created_at" min-width="200"></el-table-column>
                <!-- 移除密码和发帖数列 -->
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>





            <!-- 添加/编辑用户对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
                <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="userForm.username"></el-input>
                    </el-form-item>
                    <el-form-item label="身份" prop="role_type">
                        <el-select v-model="userForm.role_type" placeholder="请选择">
                            <el-option label="超级管理员" value="super"></el-option>
                            <el-option label="审核管理员" value="audit"></el-option>
                            <el-option label="业务管理员" value="business"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="userForm.password" type="password"
                            :placeholder="editMode ? '不修改请留空' : '请输入密码'"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="submitForm">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUsers, addUser, updateUser, deleteUser } from '@/api/user'

// 添加表单引用
const userFormRef = ref(null)

// 数据
const userList = ref([])
const total = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const searchQuery = ref('')
const dialogVisible = ref(false)
const dialogTitle = ref('')
const editMode = ref(false)
const userForm = reactive({
    id: '',
    username: '',
    role_type: '',
})


// 获取用户列表
const fetchUsers = async () => {
    loading.value = true
    try {
        const res = await getUsers()
        console.log("resGet", res);

        if (res.data.code === 200) {
            userList.value = res.data.user_list
        } else {
            ElMessage.error(res.message || '获取用户列表失败')
        }
    } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
    } finally {
        loading.value = false
    }
}


// 表单验证规则移除密码验证
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    // 可根据实际情况添加角色类型和创建时间验证
    role_type: [
        { required: true, message: '请选择角色类型', trigger: 'blur' }
    ]
}

// 添加用户
const handleAdd = () => {
    editMode.value = false
    dialogTitle.value = '添加用户'
    userForm.id = null
    userForm.username = ''
    // 新增角色类型和创建时间字段
    userForm.role_type = ''
    userForm.created_at = ''
    dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
    editMode.value = true
    dialogTitle.value = '编辑用户'
    userForm.id = row.id
    userForm.username = row.username
    // 新增角色类型和创建时间字段
    userForm.role_type = row.role_type
    userForm.created_at = row.created_at
    dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
    if (!userFormRef.value) return

    userFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                if (editMode.value) {
                    console.log('userForm :>> ', userForm);
                    const res = await updateUser(userForm)
                    console.log('resUP :>> ', res);
                    if (res.data.code === 200) {
                        ElMessage.success('更新成功')
                        dialogVisible.value = false
                        fetchUsers()
                    } else {
                        ElMessage.error(res.data.message || '更新失败')
                    }
                } else {
                    const res = await addUser(userForm)
                    // 调整判断逻辑，确保和后端返回结构一致
                    if (res.data && res.data.code === 200) { 
                        ElMessage.success('添加成功')
                        dialogVisible.value = false
                        fetchUsers()
                    } else {
                        ElMessage.error(res.data.message || '添加失败')
                    }
                }
            } catch (error) {
                console.error(editMode.value ? '更新失败:' : '添加失败:', error)
                ElMessage.error(editMode.value ? '更新失败' : '添加失败')
            }
        }
    })
}

// 修改删除处理部分
const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteUser({id:row.id})
            if (res.data.code === 200) {  // 正确访问响应数据
                ElMessage.success('删除成功')
                fetchUsers()
            } else {
                ElMessage.error(res.data.message || '删除失败')  // 获取后端返回的错误信息
            }
        } catch (error) {
            console.error('删除失败:', error)
            // 处理网络错误
            if (error.response) {
                ElMessage.error(`服务器错误: ${error.response.data.message}`)
            } else {
                ElMessage.error('网络连接异常')
            }
        }
    })
}

// 页面加载时获取用户列表
onMounted(() => {
    fetchUsers()
})
</script>

<style scoped>
.text-right {
    text-align: right;
}

.mt-4 {
    margin-top: 1rem;
}

.pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
</style>